const userService = require("../service/user.service")
const { NAME_OR_PWD_IS_REQUIRED, NAME_IS_ALREADY_EXISTS } = require("../config/error")
const md5Encryption = require("../utils/md5-encryption")

// 验证用户注册中间件
const verifyUser = async (ctx, next) => {
  const { name, password } = ctx.request.body

  if (!name || !password) {
    return ctx.app.emit('error', NAME_OR_PWD_IS_REQUIRED, ctx)
  }

  const users = await userService.findUserByName(name)
  if (users.length > 0) {
    return ctx.app.emit('error', NAME_IS_ALREADY_EXISTS, ctx)
  }
  await next()
}

// 加密存储中间件
const handlePassword = async (ctx, next) => {
  const { password } = ctx.request.body
  ctx.request.body.password = md5Encryption(password)
  await next()
}

module.exports = {
  verifyUser,
  handlePassword
}